<template>
  <!-- 弹框 -->
  <el-dialog
    :title="form.id ?'编辑用户':'添加角色'"
    :visible="visible"
    width="30%"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="form.roleDesc" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('update:visible',false)">取 消</el-button>
      <el-button type="primary" @click="addUserClick">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { postAddRoleList, postAddEditUserList } from '@/api/jurisdiction.js'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // 用户数据
      form: {
        roleName: '',
        roleDesc: ''
      },
      // 表单验证
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 18, message: '长度在 2 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {

  },

  methods: {
    // 所有关闭效果
    handleClose() {
      this.$refs.form.resetFields()
      this.form = {
        roleName: '',
        roleDesc: ''
      }
      this.$emit('update:visible', false)
    },
    // 添加用户角色
    async addUserClick() {
      await this.$refs.form.validate()
      try {
        if (this.form.id) {
          await postAddEditUserList(this.form)
          this.$message.success('修改成功')
        } else {
          await postAddRoleList(this.form)
          this.$message.success('添加成功')
        }
        this.$emit('update:visible', false)
        this.$emit('add-userclick')
      } catch (err) {
        this.$message.error('错了哦，添加失败')
      }
    },
    // 编辑用户列表
    addEditUser(row) {
      this.form = {
        roleName: row.roleName,
        roleDesc: row.roleDesc,
        id: row.id
      }
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
